package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*登录验证的过滤器*/

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        //强转为Http的request
        HttpServletRequest request = (HttpServletRequest) req;

        //判断访问路径是否与登录注册相关
        String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};

        //获取当前访问的资源路径
        String url = request.getRequestURL().toString();

        //循环判断
        for (String s : urls) {
            if (url.contains(s)){
                //找到了
                //放行
                chain.doFilter(req, resp);
                return;
            }
        }



        //1.判断session中是否有User对象
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        //2.判断user是否为空
        if (user !=null){
            //登录过了
            //放行
            chain.doFilter(req, resp);
        }else {
            //未登录,跳转登录界面
            request.setAttribute("login_msg","您尚未登录");
            request.getRequestDispatcher("login.jsp").forward(request,resp);
        }


    }

    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
